<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>事件处理示例</title>
    <style>
        .container {
            border: 2px solid black;
            padding: 20px;
            margin: 20px;
        }
        .box {
            border: 2px solid blue;
            padding: 20px;
            margin: 20px;
        }
        .button {
            border: 2px solid green;
            padding: 10px;
            margin: 10px;
            cursor: pointer;
        }
    </style>
</head>
<body>
  <div id="body">
    <div class="container" id="container">
        容器
        <div class="box" id="box">
            盒子
            <button class="button" id="button" onclick="htmlLevelHandler()">按钮</button>
        </div>
    </div>
  </div>
    <script>
        // HTML 级事件处理
        function htmlLevelHandler() {
            console.log('HTML 级事件处理：按钮被点击');
        }

        // DOM 0 级事件处理
        var button = document.getElementById('button');
        button.onclick = function() {
            console.log('DOM 0 级事件处理：按钮被点击');
        };

        // DOM 1 级事件处理
        document.getElementById('container').addEventListener('click', function(event) {
            console.log('DOM 2 级事件处理：容器捕获阶段');
        }, true);

        document.getElementById('box').addEventListener('click', function(event) {
            console.log('DOM 2 级事件处理：盒子捕获阶段');
        }, true);

        button.addEventListener('click', function(event) {
            console.log('DOM 2 级事件处理：按钮捕获阶段');
        }, true);

        document.getElementById('container').addEventListener('click', function(event) {
            console.log('DOM 2 级事件处理：容器冒泡阶段');
        }, false);

        document.getElementById('box').addEventListener('click', function(event) {
            console.log('DOM 2 级事件处理：盒子冒泡阶段');
            //event.stopPropagation(); // 阻止事件继续冒泡
        }, false);

        button.addEventListener('click', function(event) {
            console.log('DOM 2 级事件处理：按钮冒泡阶段');
        }, false);

        // 事件委托
        document.getElementById('body').addEventListener('click', function(event) {
            if (event.target && event.target.matches('button.button')) {
                console.log('事件委托：按钮被点击');
            }
        });

        // IE 事件处理   IE浏览器不支持 addEventListener 方法
        if (button.attachEvent) {
            button.attachEvent('onclick', function() {
                console.log('IE 事件处理：按钮被点击');
            });
        }
    </script>
</body>
</html>
